package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.web.admin.mapper.*;
import com.atguigu.lease.web.admin.service.*;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentDetailVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentItemVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentQueryVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentSubmitVo;
import com.atguigu.lease.web.admin.vo.fee.FeeValueVo;
import com.atguigu.lease.web.admin.vo.graph.GraphVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author liubo
 * @description 针对表【apartment_info(公寓信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class ApartmentInfoServiceImpl extends ServiceImpl<ApartmentInfoMapper, ApartmentInfo>
        implements ApartmentInfoService {
    @Autowired
    private FeeValueMapper feeValueMapper;
    @Autowired
    private ApartmentFacilityMapper apartmentFacilityMapper;
    @Autowired
    private RoomInfoMapper roomInfoMapper;
    @Autowired
    private ApartmentFacilityService apartmentFacilityService;
    @Autowired
    private ApartmentLabelService apartmentLabelService;
    @Autowired
    private ApartmentFeeValueService apartmentFeeValueService;
    @Autowired
    private GraphInfoService graphInfoService;
    @Autowired
    private LabelInfoMapper labelInfoMapper;

    @Override
    public int saveOrUpdateApartmentInfo(ApartmentSubmitVo apartmentSubmitVo) {
        boolean isUpdate = apartmentSubmitVo.getId() != null;
        // apartment_info
        this.saveOrUpdate(apartmentSubmitVo);
        if (isUpdate) {
            apartmentFacilityService.remove(Wrappers.lambdaQuery(ApartmentFacility.class)
                    .eq(ApartmentFacility::getApartmentId, apartmentSubmitVo.getId()));
            apartmentLabelService.remove(Wrappers.lambdaQuery(ApartmentLabel.class)
                    .eq(ApartmentLabel::getApartmentId, apartmentSubmitVo.getId()));
            apartmentFeeValueService.remove(Wrappers.lambdaQuery(ApartmentFeeValue.class)
                    .eq(ApartmentFeeValue::getApartmentId, apartmentSubmitVo.getId()));
            graphInfoService.remove(Wrappers.lambdaQuery(GraphInfo.class)
                    .eq(GraphInfo::getItemId, apartmentSubmitVo.getId())
                    .eq(GraphInfo::getItemType, ItemType.APARTMENT));
        }
        // apartment_facility
        if (CollectionUtils.isNotEmpty(apartmentSubmitVo.getFacilityInfoIds())) {
            List<ApartmentFacility> apartmentFacilities = apartmentSubmitVo.getFacilityInfoIds().stream().map(id -> ApartmentFacility.builder()
                    .facilityId(id)
                    .apartmentId(apartmentSubmitVo.getId())
                    .build()).collect(Collectors.toList());
            apartmentFacilityService.saveOrUpdateBatch(apartmentFacilities);
        }
        // apartment_label
        if (CollectionUtils.isNotEmpty(apartmentSubmitVo.getLabelIds())) {
            List<ApartmentLabel> apartmentLabels = apartmentSubmitVo.getLabelIds().stream().map(id -> ApartmentLabel.builder()
                    .labelId(id)
                    .apartmentId(apartmentSubmitVo.getId())
                    .build()).collect(Collectors.toList());
            apartmentLabelService.saveOrUpdateBatch(apartmentLabels);
        }
        // apartment_fee_value
        if (CollectionUtils.isNotEmpty(apartmentSubmitVo.getFeeValueIds())) {
            List<ApartmentFeeValue> apartmentFeeValues = apartmentSubmitVo.getFeeValueIds().stream().map(id -> ApartmentFeeValue.builder()
                    .feeValueId(id)
                    .apartmentId(apartmentSubmitVo.getId())
                    .build()).collect(Collectors.toList());
            apartmentFeeValueService.saveOrUpdateBatch(apartmentFeeValues);
        }
        // graph_info
        if (CollectionUtils.isNotEmpty(apartmentSubmitVo.getGraphVoList())) {
            List<GraphInfo> graphInfos = apartmentSubmitVo.getGraphVoList().stream().map(graphVo -> {
                GraphInfo graphInfo = new GraphInfo();
                BeanUtils.copyProperties(graphVo, graphInfo);
                graphInfo.setItemType(ItemType.APARTMENT);
                graphInfo.setItemId(apartmentSubmitVo.getId());
                return graphInfo;
            }).collect(Collectors.toList());
            graphInfoService.saveOrUpdateBatch(graphInfos);
        }
        return 0;
    }

    @Override
    public IPage<ApartmentItemVo> pageByCondition(long current, long size, ApartmentQueryVo queryVo) {
        // 查询公寓基本信息
        Page<ApartmentInfo> apartmentInfoPage = this.page(new Page<ApartmentInfo>(current, size), Wrappers.lambdaQuery(ApartmentInfo.class)
                .eq(queryVo.getProvinceId() != null, ApartmentInfo::getProvinceId, queryVo.getProvinceId())
                .eq(queryVo.getCityId() != null, ApartmentInfo::getCityId, queryVo.getCityId())
                .eq(queryVo.getDistrictId() != null, ApartmentInfo::getDistrictId, queryVo.getDistrictId()));
        /*// 查询房间总数
        List<ApartmentItemVo> totalRoomCountList = roomInfoMapper.getTotalRoomCount();
        // 查询空闲房间（排除已经签约的房间）
        List<ApartmentItemVo> freeRoomCountList = roomInfoMapper.getFreeRoomCount();*/
        // 查询房间总数和空闲房间数
        List<ApartmentItemVo> resultList = roomInfoMapper.getTotalRoomCountAndFreeRoomCount();
        Map<Long, ApartmentInfo> infoMap = apartmentInfoPage.getRecords().stream().collect(Collectors.toMap(BaseEntity::getId, e -> e));
        resultList.forEach(vo -> {
            BeanUtils.copyProperties(infoMap.get(vo.getId()),vo);
        });
        // 组装返回
        Page<ApartmentItemVo> resultPage = new Page<>();
        BeanUtils.copyProperties(apartmentInfoPage,resultPage);
        resultPage.setRecords(resultList);
        return resultPage;
    }

    @Override
    public ApartmentDetailVo getDetailById(Long id) {
        ApartmentInfo apartmentInfo = this.getById(id);
        List<GraphInfo> graphInfos = graphInfoService.list(Wrappers.lambdaQuery(GraphInfo.class)
                .eq(GraphInfo::getItemId, id)
                .eq(GraphInfo::getItemType, ItemType.APARTMENT));
        List<GraphVo> graphVos = Optional.ofNullable(graphInfos).orElse(new ArrayList<>()).stream()
                .map(graphInfo -> GraphVo.builder().url(graphInfo.getUrl()).name(graphInfo.getName()).build())
                .collect(Collectors.toList());
        List<LabelInfo> labelInfos = labelInfoMapper.getLabelInfoByApartmentId(id);
        List<FacilityInfo> facilityInfos = apartmentFacilityMapper.getFacilityInfoByApartmentId(id);
        List<FeeValueVo> feeValueVos = feeValueMapper.getFeeValueListByApartmentId(id);
        ApartmentDetailVo result = new ApartmentDetailVo();
        BeanUtils.copyProperties(apartmentInfo,result);
        result.setGraphVoList(graphVos);
        result.setLabelInfoList(labelInfos);
        result.setFacilityInfoList(facilityInfos);
        result.setFeeValueVoList(feeValueVos);
        return result;
    }

    @Override
    public void removeApartmentById(Long id) {
        Long count = roomInfoMapper.selectCount(Wrappers.lambdaQuery(RoomInfo.class).eq(RoomInfo::getApartmentId, id));
        if (count > 0) {
            throw new LeaseException(ResultCodeEnum.DELETE_ERROR);
        }

        // apartment_info
        this.removeById(id);
        // apartment_facility
        apartmentFacilityService.remove(Wrappers.lambdaQuery(ApartmentFacility.class).eq(ApartmentFacility::getApartmentId,id));
        // apartment_label
        apartmentLabelService.remove(Wrappers.lambdaQuery(ApartmentLabel.class).eq(ApartmentLabel::getApartmentId,id));
        // apartment_fee_value
        apartmentFeeValueService.remove(Wrappers.lambdaQuery(ApartmentFeeValue.class).eq(ApartmentFeeValue::getApartmentId,id));
        // graph_info
        graphInfoService.remove(Wrappers.lambdaQuery(GraphInfo.class).eq(GraphInfo::getItemId,id).eq(GraphInfo::getItemType,ItemType.APARTMENT));

    }
}




